//
//  GourmetDetailViewController.m
//  OrderSeat
//
//  Created by 王威 on 13-12-5.
//  Copyright (c) 2013年 wangwei. All rights reserved.
//

#import "GourmetDetailViewController.h"
#import "ShopHomeViewController.h"
#import "ComposeViewController.h"
#import "UIImageView+WebCache.h"
#import "CommentsViewController.h"
#import "LoginViewController.h"

#define BTN_LIKE_TAG 4001
#define BTN_FAV_TAG 4002
#define BTN_SHARE_TAG 4003
#define BTN_COMPOST_TAG 4004

#define LIKE_FORMAT @" 喜欢 (%@)"
#define FAV_FORMAT @" 收藏 (%@)"
#define SHARE_FORMAT @" 分享 (%@)"
#define COM_COUNT_FORMAT @"  有%@个评论"

@implementation GourmetDetailViewController

- (id)initWithId:(NSString*)gourmetId
{
    self = [super initWithNibClass:[GourmetDetailViewController class]];
    if (self) {
        self.gourmetId = gourmetId;
        _photoList = [[NSMutableArray alloc] initWithCapacity:1];
        _dataSource = [[GourmetDetailDataSource alloc] initWithVC:self];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setupUI];
}

#pragma 隐藏tabbar
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[AppDelegate sharedInstance] hideTabBar:self.tabBarController];
    
    if (!self.isLoaded || self.isBack) {
        [_dataSource fetchGourmetDetail];
        [self reset];
    }
}

- (void)setupUI
{
    [self createLeftButton];
    [self setNavigationTitle:@"美食详情"];
    
    _commentsTable.dataSource = _dataSource;
    _commentsTable.delegate = _dataSource;
    
    [UIView hiddensYES:@[_theScrollview]];
    [UIView drawBorders:@[_headView, _shopView, _commentsTable]];
    
    _theScrollview.height = ScreenHeight-NavBarHeight-StatusBarHeight;
}

- (void)leftButtonClick:(id)sender
{
    [[AppDelegate sharedInstance] showTabBar:self.tabBarController];
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)buttonAction:(id)sender
{
    if (![self checkFormForTag:[sender tag]]) return;
    
    if ([sender tag] == BTN_LIKE_TAG) {
        [_dataSource like];
    }
    if ([sender tag] == BTN_FAV_TAG) {
        if(![AppDelegate checkLoginWithDelegate:self])return;
        [_dataSource favorites];
    }
    if ([sender tag] == BTN_SHARE_TAG) {
        [_dataSource share];
    }
    if ([sender tag] == BTN_COMPOST_TAG) {
        [self compostAction];
    }
}

- (BOOL)checkFormForTag:(int)tag
{
    if (tag == BTN_LIKE_TAG && _likeBtn.selected) {
        [AppDelegate showMessage:@"亲，每天只能喜欢一次吆"];
        return NO;
    }
    if (tag == BTN_FAV_TAG && ![AppDelegate checkLoginWithDelegate:self]) {
        return NO;
    }
    if (tag == BTN_FAV_TAG && _favBtn.selected) {
        [AppDelegate showMessage:@"亲，您已经收藏过了"];
        return NO;
    }
    
    return YES;
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    LoginViewController *loginVC = [[LoginViewController alloc] init];
    loginVC.backController = self;
    [self.navigationController pushViewController:loginVC animated:YES];
}

- (void)compostAction
{
    if(![AppDelegate checkLoginWithDelegate:self]) return;
    
    ComposeViewController *compostVC = [[ComposeViewController alloc] initWithId:_gourmetId forType:Gourmet];
    compostVC.parentVC = self;
    [self.navigationController pushViewController:compostVC animated:YES];
}

- (IBAction)orderAction:(id)sender
{
    ShopHomeViewController *shopHomeVC = [[ShopHomeViewController alloc] initWithId:_shopId];
    [AppDelegate changeToShopTabBar:shopHomeVC];
    [self.navigationController pushViewController:shopHomeVC animated:YES];
}

- (void)opration:(OprationType)type count:(NSString*)count
{
    if (type == Like) {
        NSString *likeText = [NSString stringWithFormat:LIKE_FORMAT,count];
        [_likeBtn setTitleForNormal:likeText];
        _likeBtn.selected = YES;
        
        [[DbManager sharedManager] insertLike:_gourmetId type:GourmetLikeType];
    }
    if (type == Favorites) {
        NSString *favText = [NSString stringWithFormat:FAV_FORMAT,count];
        [_favBtn setTitleForNormal:favText];
        _favBtn.selected = YES;
    }
}

- (void)setFormValues:(NSDictionary*)data
{
    NSLog(@"data:%@", data);
    self.data = [NSMutableDictionary dictionaryWithDictionary:data];
    self.shopId = [data objectForKey:@"did"];
    NSString *likeCount = [data objectForKey:@"xihuan"];
    NSString *favCount = [data objectForKey:@"shoucangshu"];
    NSString *shareCount = [data objectForKey:@"fenxiang"];
    NSString *commCount = [data objectForKey:@"dianpingshu"];
    
    NSString *likeText = [NSString stringWithFormat:LIKE_FORMAT,likeCount];
    NSString *favText = [NSString stringWithFormat:FAV_FORMAT,favCount];
    NSString *shareText = [NSString stringWithFormat:SHARE_FORMAT,shareCount];
    NSString *commText = [NSString stringWithFormat:COM_COUNT_FORMAT,commCount];
    BOOL isFav = [[data objectForKey:@"ifshoucang"] intValue] > 0;
    
    [_logoImage setImageWithURL:[NSURL URLWithString:[data objectForKey:@"image"]]];
    [_logoImage addTarget:self action:@selector(ImageTapped:)];
    
    _titleLabel.text = [data objectForKey:@"title"];
    _descriptionLabel.text = [data objectForKey:@"content"];
    _tagLabel.text = [data objectForKey:@"biaoqian"];
    
    _favBtn.selected = isFav;
    [_likeBtn setTitleForNormal:likeText];
    [_favBtn setTitleForNormal:favText];
    [_shareBtn setTitleForNormal:shareText];
    _commentCountLabel.text = commText;
    
    [_commentsTable reloadData];
    [_commentsTable addTarget:self action:@selector(viewCommentsAction:)];
    
    [self reLayoutSubviews];
}

- (void)viewCommentsAction:(id)sender
{
    CommentsViewController *commVC = [[CommentsViewController alloc] initWithId:_gourmetId andType:GourmetCommType];
    [self.navigationController pushViewController:commVC animated:YES];
}

- (void)reLayoutSubviews
{
    _likeBtn.selected = [[DbManager sharedManager] isLike:_gourmetId type:GourmetLikeType];
    [UIView hiddenNO:@[_theScrollview]];
    
    [_descriptionLabel autoLabelSize];
    
    _likeBtn.top = _favBtn.top = _shareBtn.top = _descriptionLabel.bottom_5;
    
    [UIView autoHeights:@[_headView,_commentsTable]];
    [UIView autoLayoutVertical:@[_headView, _shopView, _commentsTable]];
    
    [_theScrollview autoContentHeight];
}

- (void)shareWithData:(NSDictionary *)data
{
    NSString *content = [data objectForKey:@"content"];
    NSString *imageURL = [data objectForKey:@"image"];
    NSString *fxLink = [data objectForKey:@"fxlink"];
    
    [AppDelegate shareWithContent:content andImageURL:imageURL andLink:fxLink];
}

- (void)ImageTapped:(id)sender
{
    NSLog(@"data:%@", self.data);
    NSString *url = [self.data objectForKey:@"image"];
    NSString *content = [self.data objectForKey:@"content"];
    
    MWPhoto *photo = [MWPhoto photoWithURL:[NSURL URLWithString:url]];
    photo.caption = content;
    [_photoList addObject:photo];
    
    MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
    browser.displayActionButton = NO;
    browser.displayNavArrows = YES;
    browser.displaySelectionButtons = NO;
    browser.alwaysShowControls = NO;
    browser.wantsFullScreenLayout = YES;
    browser.zoomPhotosToFill = YES;
    browser.enableGrid = NO;
    browser.startOnGrid = NO;
    [browser setCurrentPhotoIndex:0];
    
    UINavigationController *nc = [[UINavigationController alloc] initWithRootViewController:browser];
    nc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentModalViewController:nc animated:YES];
}

#pragma mark - MWPhotoBrowserDelegate
- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
    return 1;
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    if (index < _photoList.count)
        return [_photoList objectAtIndex:index];
    return nil;
}

@end

//==========================================================================================
#pragma ===================数据源类实现=======================================================
//==========================================================================================

@implementation GourmetDetailDataSource

#define FETCH_GOURMET_TAG 2001
#define GOURMET_LIKE_TAG 3003
#define GOURMET_FAVORITES_TAG 3004
#define GOURMET_SHARE_TAG 3005

#define SimpleCommentsCellId    @"SimpleCommentsCell"

- (id)initWithVC:(id)viewController
{
    self = [super init];
    if (self) {
        self.viewController = viewController;
        _commentsList = [[NSMutableArray alloc] initWithCapacity:5];
        self.commentCell = [_viewController createCellWithNib:SimpleCommentsCellId];
    }
    return self;
}

- (void)fetchGourmetDetail
{
    [SVProgressHUD show];
    NSString *url = [NSString stringWithFormat:API_GOURMET_DETAIL,_viewController.gourmetId,[AppSetting userName]];
    [self get:url tag:FETCH_GOURMET_TAG];
}

- (void)like
{
    [SVProgressHUD show];
    NSString *url = [NSString stringWithFormat:API_GOURMET_LIKE, _viewController.gourmetId];
    [self get:url tag:GOURMET_LIKE_TAG];
}

- (void)favorites
{
    [SVProgressHUD show];
    NSString *url = [NSString stringWithFormat:API_GOURMET_FAVORITES, _viewController.gourmetId,[AppSetting userName]];
    [self get:url tag:GOURMET_FAVORITES_TAG];
}

- (void)share
{
    NSString *url = [NSString stringWithFormat:API_GOURMET_SHARES, _viewController.gourmetId];
    [self get:url tag:GOURMET_SHARE_TAG];
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
    CLog(@"%@", request.responseString);
    NSDictionary *json = [request.responseData JSONValue];
    if ([[json objectForKey:@"error_code"] intValue] != 0) {
        return;
    }
    
    NSDictionary *data = [json objectForKey:@"data"];
    if (request.tag == FETCH_GOURMET_TAG) {
        self.commentsList = [data objectForKey:@"pinglun"];
        [_viewController setFormValues:data];
        [SVProgressHUD dismiss];
    }
    
    if (request.tag == GOURMET_LIKE_TAG) {
        int state = [[data objectForKey:@"state"] intValue];
        if (state == 1) {
            NSString *likeCount = [data objectForKey:@"xihuan"];
            [_viewController opration:Like count:likeCount];
        }
        
        [SVProgressHUD dismiss];
    }
    
    if (request.tag == GOURMET_FAVORITES_TAG) {
        int state = [[data objectForKey:@"state"] intValue];
        if (state == 1) {
            NSString *favCount = [data objectForKey:@"shoucang"];
            [_viewController opration:Favorites count:favCount];
        }
        if (state == 2) {
            [SVProgressHUD dismissWithSuccess:@"您已经收藏过了"];
        }
        
        [SVProgressHUD dismiss];
    }
    
    if (request.tag == GOURMET_SHARE_TAG) {
        [_viewController shareWithData:data];
    }
}

#pragma ===================加载tableview数据 Begin=================================

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [_commentCell getCellHeight:[_commentsList objectAtIndex:indexPath.row]];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _commentsList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SimpleCommentsCell *cell = [self.viewController createCellWithNib:SimpleCommentsCellId tableview:tableView];
    
    [cell setContent:[_commentsList objectAtIndex:indexPath.row]];
    
    return cell;
}

@end
